package com.example.springbootweb_comprehensiveexample.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootweb_comprehensiveexample.mapper.OperateLogMapper;
import com.example.springbootweb_comprehensiveexample.pojo.OperateLog;
import com.example.springbootweb_comprehensiveexample.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect//指定此类为切面类
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.springbootweb_comprehensiveexample.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //！！！通过JWT令牌中包含的登录员工的信息来填表！！！
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);

        //1.操作人ID - 当前登录员工的ID
        Integer operateUser = (Integer) claims.get("id");

        //2.操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //3.操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //4.操作方法名
        String methodName = joinPoint.getSignature().getName();

        //5.操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

            //记录开始时间
            long begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
            //记录结束时间
            long end = System.currentTimeMillis();

        //6.操作方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //7.操作耗时
        Long costTime = end - begin;

        //记录操作日志
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志：{}", operateLog);

        return result;
    }

}
